﻿<%@ WebHandler Language="C#" Class="ImageProcess" %>

using System;
using System.IO;
using System.Data;
using System.Collections;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;

using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;

/// <summary>
/// Summary description for $codebehindclassname$
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class ImageProcess : IHttpHandler
{
    string _strNoImage = "~/Admin/images/Items/NoImage.jpg";
    int iDefaultWidth = 135;
    int iDefaultHeight = 100;
    public void ProcessRequest(HttpContext context)
    {
        string imgpath = string.Empty;
        Image.GetThumbnailImageAbort callback = null;
        //IntPtr callbackData = new System.IntPtr();
        Image thumbnailimg;
        Image largeimg = null;
        if (context.Request["file"] != null)
            imgpath = context.Server.UrlDecode(context.Request["file"]);
        try
        {
            largeimg = Image.FromFile(context.Server.MapPath(imgpath));
        }
        catch
        {
            largeimg = Image.FromFile(context.Server.MapPath(_strNoImage));
        }

        int iWidth = largeimg.Width;
        int iHeight = largeimg.Height;
        bool bDefaultDimension = false;
        if (context.Request["dd"] != null)
            bDefaultDimension = true;

        if ((context.Request["width"] != null) && (context.Request["height"] != null))
        {
            if (largeimg.Width >= largeimg.Height)
            {
                try
                {
                    iWidth = Convert.ToInt16(context.Server.UrlDecode(context.Request["width"]));
                    iHeight = CalculateRatioByWidth(largeimg.Width, largeimg.Height, iWidth);
                    if (bDefaultDimension)
                    {
                        iDefaultHeight = CalculateRatioByWidth(iDefaultWidth, iDefaultHeight, iWidth);
                        iDefaultWidth = iWidth;
                    }                    
                    
                    if (iHeight > Convert.ToInt16(context.Server.UrlDecode(context.Request["height"])))
                    {
                        iHeight = Convert.ToInt16(context.Server.UrlDecode(context.Request["height"]));
                        iWidth = CalculateRatioByHeight(largeimg.Width, largeimg.Height, iHeight);
                        if (bDefaultDimension)
                        {
                            iDefaultWidth = CalculateRatioByHeight(iDefaultWidth, iDefaultHeight, iHeight);
                            iDefaultHeight = iHeight;
                        }
                    }
                }
                catch (Exception)
                {
                    iWidth = largeimg.Width;
                    iHeight = largeimg.Height;
                }
            }
            else if ((largeimg.Width < largeimg.Height))
            {
                try
                {
                    iHeight = Convert.ToInt16(context.Server.UrlDecode(context.Request["height"]));
                    iWidth = CalculateRatioByHeight(largeimg.Width, largeimg.Height, iHeight);

                    if (bDefaultDimension)
                    {
                        iDefaultWidth = CalculateRatioByHeight(iDefaultWidth, iDefaultHeight, iHeight);
                        iDefaultHeight = iHeight;
                    }
                    
                    if (iWidth > Convert.ToInt16(context.Server.UrlDecode(context.Request["width"])))
                    {
                        iWidth = Convert.ToInt16(context.Server.UrlDecode(context.Request["width"]));
                        iHeight = CalculateRatioByWidth(largeimg.Width, largeimg.Height, iWidth);
                        if (bDefaultDimension)
                        {
                            iDefaultHeight = CalculateRatioByWidth(iDefaultWidth, iDefaultHeight, iWidth);
                            iDefaultWidth = iWidth;
                        }
                    }
                }
                catch (Exception)
                {
                    iWidth = largeimg.Width;
                    iHeight = largeimg.Height;
                }
            }
        }
        else
        {
            if (context.Request["width"] != null)
            {
                try
                {
                    iWidth = Convert.ToInt16(context.Server.UrlDecode(context.Request["width"]));
                    iHeight = CalculateRatioByWidth(largeimg.Width, largeimg.Height, iWidth);
                    if (bDefaultDimension)
                    {
                        iDefaultHeight = CalculateRatioByWidth(iDefaultWidth, iDefaultHeight, iWidth);
                        iDefaultWidth = iWidth;
                    }
                }
                catch (Exception)
                {
                    iWidth = largeimg.Width;
                    iHeight = largeimg.Height;
                }
            }

            else if (context.Request["height"] != null)
            {
                try
                {
                    iHeight = Convert.ToInt16(context.Server.UrlDecode(context.Request["height"]));
                    iWidth = CalculateRatioByHeight(largeimg.Width, largeimg.Height, iHeight);
                    if (bDefaultDimension)
                    {
                        iDefaultWidth = CalculateRatioByHeight(iDefaultWidth, iDefaultHeight, iHeight);
                        iDefaultHeight = iHeight;
                    }
                }
                catch (Exception)
                {
                    iWidth = largeimg.Width;
                    iHeight = largeimg.Height;
                }
            }
        }

        //thumbnailimg= largeimg.GetThumbnailImage(iWidth, iHeight, null, callbackData);
        if (!bDefaultDimension)
            thumbnailimg = ResizeImage(largeimg, iWidth, iHeight, 0, 0, ImageFormat.Jpeg);
        else
        {
            int iX = 0;
            int iY = 0;
            if (iWidth < iDefaultWidth)
                iX = (iDefaultWidth - iWidth) / 2;
            if (iHeight < iDefaultHeight)
                iY = (iDefaultHeight - iHeight) / 2;
            thumbnailimg = ResizeImageByDefaultDimension(largeimg, iWidth, iHeight, iDefaultWidth, iDefaultHeight, iX, iY, ImageFormat.Jpeg);
        }

        if (context.Request["isVideoImg"] != null)
        {
            try
            {
                if (Convert.ToBoolean(context.Request["isVideoImg"]))
                {
                    string strFrameVideoFilePath = context.Server.MapPath("~/images/FrameVideo.png");
                    if (File.Exists(strFrameVideoFilePath))
                        thumbnailimg = DrawVideoFrame(thumbnailimg, strFrameVideoFilePath);
                }
            }
            catch (Exception)
            {
            }
        }


        ImageCodecInfo[] info = ImageCodecInfo.GetImageEncoders();
        EncoderParameters encoderParameters;
        encoderParameters = new EncoderParameters(1);
        encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 100L);

        //context.Response.ContentType = "image/jpeg";
        //thumbnailimg.Save(context.Response.OutputStream, info[1], encoderParameters);

        using (System.IO.MemoryStream mem = new System.IO.MemoryStream())
        {
            thumbnailimg.Save(mem, ImageFormat.Png);
            mem.WriteTo(context.Response.OutputStream);
        }

        thumbnailimg.Dispose();
        largeimg.Dispose();
    }

    public Image ResizeImage(Image originalImage, int width, int height, int iX, int iY, ImageFormat format)
    {
        Image finalImage = new Bitmap(width, height);
        //Bitmap img = new Bitmap(originalImage);
        //img.MakeTransparent(Color.Transparent);
        //finalImage = img.GetThumbnailImage(width, height, new Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero);

        Graphics graphic = Graphics.FromImage(finalImage);

        graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
        graphic.SmoothingMode = SmoothingMode.HighQuality;
        graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
        graphic.CompositingQuality = CompositingQuality.HighQuality;

        Rectangle rectangle = new Rectangle(iX, iY, width, height);

        graphic.DrawImage(originalImage, rectangle);

        //finalImage.Save("D:\\a.png", ImageFormat.Png);

        return finalImage;
    }

    public Image ResizeImageByDefaultDimension(Image originalImage, int width, int height, int DefaultWidth, int DefaultHeight, int iX, int iY, ImageFormat format)
    {
        Image finalImage = new Bitmap(DefaultWidth, DefaultHeight);

        Graphics graphic = Graphics.FromImage(finalImage);
        SolidBrush sb = new SolidBrush(Color.White);
        graphic.FillRectangle(sb, new Rectangle(0, 0, DefaultWidth, DefaultHeight));

        graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
        graphic.SmoothingMode = SmoothingMode.HighQuality;
        graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
        graphic.CompositingQuality = CompositingQuality.HighQuality;

        Rectangle rectangle = new Rectangle(iX, iY, width, height);

        graphic.DrawImage(originalImage, rectangle);

        return finalImage;
    }

    public Image DrawVideoFrame(Image OriginalImage, string VideoFrameFilePath)
    {
        Image finalImage = Image.FromFile(VideoFrameFilePath);

        Graphics graphic = Graphics.FromImage(finalImage);

        graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
        graphic.SmoothingMode = SmoothingMode.HighQuality;
        graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
        graphic.CompositingQuality = CompositingQuality.HighQuality;

        Rectangle rectangle = new Rectangle(5, 5, OriginalImage.Width, finalImage.Height - 36);

        graphic.DrawImage(OriginalImage, rectangle);

        return finalImage;
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

    #region Private Methods
    private int CalculateRatioByWidth(int OriginalWidth, int OriginalHeight, int Width)
    {
        try
        {

            int iHeight = OriginalHeight;
            float fRatio = (float)Width / (float)OriginalWidth;
            iHeight = Convert.ToInt16(Math.Round(fRatio * OriginalHeight, 0));
            return iHeight;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    private int CalculateRatioByHeight(int OriginalWidth, int OriginalHeight, int Height)
    {
        try
        {
            int iWidth = OriginalWidth;
            float fRatio = (float)Height / (float)OriginalHeight;
            iWidth = Convert.ToInt16(Math.Round(fRatio * OriginalWidth, 0));
            return iWidth;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    private bool ThumbnailCallback()
    {
        return true;
    }
    #endregion
}